﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace DataCodeDemo.Servers
{
    public abstract class SocketObject
    {
        public abstract void InitSocket(IPAddress ip, int port);
        public abstract void InitSocket(string ip, int port);
        public abstract int Start();
        public abstract void Stop();

        /// <summary>
        /// 解析域名
        /// </summary>
        protected string DomainName(string strDomain)
        {
            IPHostEntry host = Dns.GetHostEntry(strDomain);
            IPAddress ip = host.AddressList[0];
            return ip.ToString();
        }

        /// <summary>
        /// 验证ip地址是否是连接
        /// </summary>
        protected string ExistIp(string ip)
        {
            Match m = Regex.Match(ip, @"((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))");   // 匹配正则表达式
            if (!m.Success)
            {
                return DomainName(ip);
            }
            else
            {
                return ip;
            }
        }

        public event EventHandler<RecvMsgEventArgs> OnRecvMsg;
        protected void InvokeRecvMsg(object sender, RecvMsgEventArgs e)
        {
            OnRecvMsg?.Invoke(sender, e);
        }
    }

    public class RecvMsgEventArgs:EventArgs
    {
        public Socket ClientSocket { get; set; }
        public byte[] Msg { get; set; }
    }
}
